package com.jason.ladder.interceptor;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.jason.ladder.Constants;

public class SessionInterceptor implements HandlerInterceptor {

private String[] pagesThatDoNotRequireAuthentication;
private static Logger logger = Logger.getLogger( SessionInterceptor.class );

/*
 * @see org.springframework.web.servlet.HandlerInterceptor
 *             #preHandle(HttpServletRequest, HttpServletResponse, Object)
 */
public boolean preHandle(HttpServletRequest request,
                                  HttpServletResponse response,
                                  Object handler) throws Exception {
logger.warn("In prehandle");
    /* first, check if the requested view even required authentication */
    if (isAuthenticationRequired(request)) {        

        /* check to see that user is logged in */
        if (null == request.getSession().getAttribute(Constants.SESSION_USER)) {
        	logger.warn("sending to login screen");
            return forwardToLogonPage(request, response);
        }
logger.warn("all in okay in interceptor");
        /* all is ok - pass the request on */
        return true;
    }
	return true;
}

/**
 * determines if the view that was requested requires the user to be authenticated
 *
 * @param request HttpServletRequest
 * @return boolean flase if the requested view
 *                       is in pagesThatDoNotRequireAuthentication
 */
private boolean isAuthenticationRequired(final HttpServletRequest request) {    

    String contextPath = request.getRequestURL().toString();
    //boolean returnValue = true;
    for (int i = 0; i < pagesThatDoNotRequireAuthentication.length; i++) {

        String page = pagesThatDoNotRequireAuthentication[i];

        if (0 < contextPath.indexOf(page)) {
            return false;
        }
    }

    return true;

}

/**
 * sends a redirect to the login page
 */
private boolean forwardToLogonPage(HttpServletRequest request,
                                   HttpServletResponse response)
                                                      throws IOException {
	
    response.sendRedirect(response.encodeRedirectURL("/index.jsp"));
    return false;
}

public void setPagesThatDoNotRequireAuthentication(String[] pages) {
    this.pagesThatDoNotRequireAuthentication = pages;
}

@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1,
		Object arg2, Exception arg3) throws Exception {

}

@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
		Object arg2, ModelAndView arg3) throws Exception {
	// TODO Auto-generated method stub
	
}


}